//
//  SKSinaWeiBoV2.m
//  ShareKit4QC
//
//  Created by 凯 赵 on 12-5-7.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "SHKSinaWeiBoV2.h"
#import "SHK.h"
#import "NSString+URLEncoding.h"
#import "SHKSinaWeiboV2OAuthView.h"
#import "JSONKit.h"
#import "NSHTTPCookieStorage+DeleteForURL.h"


static NSString *authorizeURL = @"https://api.weibo.com/oauth2/authorize";
//app key 信息
//static NSString* sinaWeiboV2ClientId =@"2288931787";
//static NSString* sinaWeiboV2SecretKey =@"cef420c52d554990434a67741d95d71c";

//app key 掌上千尺
static NSString* sinaWeiboV2ClientId =@"1022866087";
static NSString* sinaWeiboV2SecretKey =@"b94278f21c1ffb4568d3d5439fd2898f";
static NSString* sinaWeiboV2RedirectURI =@"http://1000chi.com";
//鉴权信息
static NSString *accessTokenKey = @"accessToken";
static NSString *uidKey=@"uid";
static NSString *expires_inKey=@"expires_in";

@interface SinaWeiBoV2()
- (void)storeAccessToken;
- (BOOL)restoreAccessToken;
- (void)deleteStoredAccessToken;
- (BOOL)authorize;
- (void)promptAuthorization;
@property (nonatomic, strong) NSString *accessToken;
@property (nonatomic, strong) NSString *uid;
@property (nonatomic, assign) NSTimeInterval expires_Time;
@end

@implementation SinaWeiBoV2
@synthesize accessToken = _accessToken;
@synthesize uid = _uid;
@synthesize expires_Time=_expires_Time;

#pragma mark – init
+ (id) sharedInstance {
    static dispatch_once_t onceToken = 0;
    __strong static id _sharedObject = nil;
    dispatch_once(&onceToken, ^{
        _sharedObject = [[SinaWeiBoV2 alloc]initWithHostName:@"api.weibo.com/2" apiPath:nil customHeaderFields:nil];
    });
    return _sharedObject;
}
- (NSString *)sharerId
{
    return @"SinaWeiboV2";
}
- (NSString *)sharerName
{
    return @"新浪微薄";
}
- (void) logout
{
    [NSHTTPCookieStorage deleteCookiesForURL:[NSURL URLWithString:authorizeURL]];
    return [self deleteStoredAccessToken];
}
- (BOOL)islogin
{
    return [self isAuthorized];
}
- (BOOL)autologin
{
    return [self authorize];
}

#pragma mark – OAuth 过程
- (void)storeAccessToken
{	
	NSString *sharerId = [self sharerId];
	[SHK setAuthValue:self.accessToken forKey:accessTokenKey forSharer:sharerId];
    [SHK setAuthValue:self.uid forKey:uidKey forSharer:sharerId];
    [SHK setAuthValue:[NSString stringWithFormat:@"%lf", self.expires_Time] forKey:expires_inKey forSharer:sharerId];
}

- (BOOL)restoreAccessToken
{
    if (self.expires_Time>0 && [[NSDate date] timeIntervalSince1970] > self.expires_Time){
        //时间过期，强制logout 
        [self deleteStoredAccessToken];
        return NO;
    }
    
	if (self.accessToken != nil && self.uid !=nil && self.expires_Time != 0 &&[[NSDate date] timeIntervalSince1970] < self.expires_Time)
		return YES;//不过期
    
    NSString *sharerId = [self sharerId];
	self.accessToken = [SHK getAuthValueForKey:accessTokenKey forSharer:sharerId];
    self.uid = [SHK getAuthValueForKey:uidKey forSharer:sharerId];
    self.expires_Time = [[SHK getAuthValueForKey:expires_inKey forSharer:sharerId]doubleValue];
	
    if ([[NSDate date] timeIntervalSince1970] > self.expires_Time){
        //时间过期，强制logout 
        [self deleteStoredAccessToken];
        return NO;
    }
    
	return (self.accessToken != nil)&&(self.uid != nil)&&(self.expires_Time !=0 &&[[NSDate date] timeIntervalSince1970] < self.expires_Time);
}

- (void)deleteStoredAccessToken
{
	NSString *sharerId = [self sharerId];
	
    [SHK removeAuthValueForKey:accessTokenKey forSharer:sharerId];
    [SHK removeAuthValueForKey:uidKey forSharer:sharerId];
    [SHK removeAuthValueForKey:expires_inKey forSharer:sharerId];
    
    self.accessToken =nil;
    self.uid=nil;
    self.expires_Time=0;
}

- (BOOL)isAuthorized
{		
	return [self restoreAccessToken];
}

- (void)promptAuthorization
{
    NSURL* callbackURL=[NSURL URLWithString:sinaWeiboV2RedirectURI];
	NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?display=mobile&client_id=%@&response_type=code&redirect_uri=%@", authorizeURL, sinaWeiboV2ClientId, [callbackURL.absoluteString URLEncodedString]]];
    
	SHKSinaWeiboV2OAuthView *auth = [[SHKSinaWeiboV2OAuthView alloc] initWithURL:url delegate:self];
	[[SHK currentHelper] showViewController:auth];	
	//[auth release];
}
- (void)tokenAuthorizeView:(SHKOAuthView *)authView didFinishWithSuccess:(BOOL)success queryParams:(NSMutableDictionary *)queryParams error:(NSError *)error
{
#warning 无网络状态下，授权页面会授权失败，此时，是否应该有所提示呢？
    if (!success && error) {
        NSLog(@"%@",[error localizedDescription]);
        [[SHK currentHelper] hideCurrentViewControllerAnimated:YES];
    }
    NSLog(@"tokenAuthorizeView");
}

- (NSURL *)authorizeCallbackURL
{
    NSLog(@"authorizeCallbackURL");
    return [NSURL URLWithString:sinaWeiboV2RedirectURI];
}
- (BOOL)authorize
{
	if ([self isAuthorized])
		return YES;
	
	else 
		[self promptAuthorization];
	
	return NO;
}

- (void)tokenAuthorizeCancelledView:(SHKOAuthView *)authView
{
	[[SHK currentHelper] hideCurrentViewControllerAnimated:YES];	
    //[self authDidFinish:NO];
}

- (void)requestAccessTokenWithAuthorizeCode:(NSString *)code
{
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:sinaWeiboV2ClientId, @"client_id",
                            sinaWeiboV2SecretKey, @"client_secret",
                            @"authorization_code", @"grant_type",
                            sinaWeiboV2RedirectURI, @"redirect_uri",
                            code, @"code", nil];
    
    //注意：获取token的apipath 与微薄功能调用api 路径不一致
    //https://api.weibo.com/oauth2/access_token 
    MKNetworkOperation *op = [self operationWithURLString:@"https://api.weibo.com/oauth2/access_token"
                                              params:params
                                               httpMethod:@"POST"];//
    
    [op onCompletion:^(MKNetworkOperation *completedOperation)
     {
         // the completionBlock will be called twice. 
         // if you are interested only in new values, move that code within the else block
         
         if([completedOperation isCachedResponse]) {
             DLog(@"Data from cache %@", [completedOperation responseJSON]);
         }
         else {
             DLog(@"Data from server %@", [completedOperation responseString]);
         }
         
         [[SHK currentHelper] hideCurrentViewControllerAnimated:YES];
         
         BOOL success = NO;
         
         NSMutableDictionary* dict = [[completedOperation responseString] objectFromJSONString];
         //NSDictionary *dict = (NSDictionary *)[completedOperation responseJSON] ;采用mknetwork的json解析，在这里会解析错误
         if ([dict isKindOfClass:[NSDictionary class]])
         {
             NSString *token = [dict objectForKey:@"access_token"];
             NSString *userID = [dict objectForKey:@"uid"];
             NSInteger seconds = [[dict objectForKey:@"expires_in"] intValue];
             
             success = token && userID&&seconds;
             if (success) {
                 self.accessToken = token;
                 self.uid = userID;
                 self.expires_Time = [[NSDate date] timeIntervalSince1970] + seconds;
                 [self storeAccessToken];
                 
                 // [self tryPendingAction];
                // [self tryToSend];
             }
         }
         
         
     }onError:^(MKNetworkOperation *completedOperation, NSError* error) {
         
         DLog(@"Data from server %@", [completedOperation responseString]);
     }];
    
    [self enqueueOperation:op forceReload:YES];//强制请求
    
}
- (void)authorizeWebView:(SHKSinaWeiboV2OAuthView *)webView didReceiveAuthorizeCode:(NSString *)code
{
    // 授权过程被 取消
    if (![code isEqualToString:@"21330"])
    {
        [self requestAccessTokenWithAuthorizeCode:code];
    }
    else 
    {
        [[SHK currentHelper] hideCurrentViewControllerAnimated:YES];
    }
}

#pragma mark – API接口
-(MKNetworkOperation*)  requestAPI:(NSString*)apiPath
                        httpMethod:(NSString *)httpMethod
                            params:(NSDictionary *)params
                      onCompletion:(SinaWeiBoV2ResponseBlock) completionBlock
                           onError:(SinaWeiBoV2ErrorBlock) errorBlock{
    
    if (![self authorize]) {
        return nil;
    }
    NSMutableDictionary *mutableParams = [NSMutableDictionary dictionaryWithDictionary:params];
    [mutableParams setObject:self.accessToken forKey:@"access_token"];
    
    MKNetworkOperation *op = [self operationWithPath:apiPath
                                              params:mutableParams
                                          httpMethod:httpMethod
                                                 ssl:YES];//强制使用https
    NSLog(@"%@",[op curlCommandLineString]);
    [op onCompletion:^(MKNetworkOperation *completedOperation)
     {
         completionBlock([[completedOperation responseString]objectFromJSONString]);
         
     }onError:^(MKNetworkOperation *completedOperation, NSError* error) {
         //============临时处理======
         NSMutableDictionary* dict = [[completedOperation responseString] objectFromJSONString];
         if ([dict isKindOfClass:[NSDictionary class]])
         {
             int error_code = [[dict objectForKey:@"error_code"] intValue] ;
             NSString* error= [dict objectForKey:@"error"];
             switch (error_code) {
                 case 21327:
                     NSLog(@"%@,%d",error,error_code);
                     
                     [self deleteStoredAccessToken];
                     break;
                     
                 default:
                     break;
             }
             
         }
         //========================
         errorBlock([[completedOperation responseString]objectFromJSONString], error);
     }];
    
    [self enqueueOperation:op forceReload:YES];//强制请求
    
    return op;
}

-(MKNetworkOperation*)  update:(NSString*)text
                         image:(UIImage *)image
                  onCompletion:(SinaWeiBoV2ResponseBlock) completionBlock
                       onError:(SinaWeiBoV2ErrorBlock) errorBlock{
    
    if (![self authorize]) {
        return nil;
    }
    NSMutableDictionary *mutableParams = [NSMutableDictionary dictionaryWithDictionary:nil];
    [mutableParams setObject:self.accessToken forKey:@"access_token"];
    
    [mutableParams setObject:(text ? text : @"") forKey:@"status"];
    
    NSString* apiPath=@"";
    if (image) {
        apiPath=@"statuses/upload.json";
    }else{
        apiPath=@"statuses/update.json";
    }
    
    MKNetworkOperation *op = [self operationWithPath:apiPath
                                              params:mutableParams
                                          httpMethod:@"POST"
                                                 ssl:YES];//强制使用https
    
    if (image) {
        NSData* imageData = UIImagePNGRepresentation((UIImage *)image);
        [op addData:imageData forKey:@"pic" fileName:@"file.png" mimeType:@"image/png"];
        // setFreezable uploads your images after connection is restored!
        [op setFreezable:YES];
    }
    [op onCompletion:^(MKNetworkOperation *completedOperation)
     {
         completionBlock([[completedOperation responseString]objectFromJSONString]);
         
     }onError:^(MKNetworkOperation *completedOperation, NSError* error) {
         
         errorBlock([[completedOperation responseString]objectFromJSONString], error);
     }];
    
    [self enqueueOperation:op forceReload:YES];//强制请求
    
    return op;
}

//========================================
/*
-(void)getSinaOauth2FriendsTimeLine{
    
    if (![[SinaWeiBoV2 sharedInstance] islogin]) {
        [MBProgressHUD showHUDAddedTo:self.tableview animated:YES];//如果授权不成功，则任何功能性请求都会直接改为去授权验证。
    }
    // [MBProgressHUD showHUDAddedTo:self.tableview animated:YES];
    
    //=========================================================================
    //http://open.weibo.com/wiki/2/statuses/home_timeline
    //since_id	false	int64	若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    //max_id	false	int64	若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
    //count	false	int	单页返回的记录条数，默认为50。
    //page	false	int	返回结果的页码，默认为1。
    //base_app	false	int	是否只获取当前应用的数据。0为否（所有数据），1为是（仅当前应用），默认为0。
    //feature	false	int	过滤类型ID，0：全部、1：原创、2：图片、3：视频、4：音乐，默认为0。
    //==========================================================================
    NSString* apiPath=@"statuses/home_timeline.json";
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                            @"200",@"count",//获取条目数
                            @"2",@"feature",//获取图片
                            nil];
    
    MKNetworkOperation* op= [ [SinaWeiBoV2 sharedInstance]  requestAPI:apiPath
                                                            httpMethod:@"GET"
                                                                params:params
                                                          onCompletion:^(NSDictionary* responseData){
                                                              //dosomething
                                                              NSLog(@"success");
                                                              if ([responseData isKindOfClass:[NSDictionary class]]){
                                                                  WeiBoSource *source = [[WeiBoSource alloc] initWithDictionary:responseData];
                                                                  
                                                                  NSLog(@"weibosource.imageUrlArray: %@",source.imageUrlArray);
                                                                  
                                                                  self.weibosource = source;
                                                                  
                                                                  [tableview reloadData];
                                                                  [MBProgressHUD hideHUDForView:self.tableview animated:YES];
                                                              }
                                                              
                                                          }onError:^(NSDictionary* responseData, NSError *error){
                                                              //dosomething
                                                              NSLog(@"error");
                                                              [MBProgressHUD hideHUDForView:self.tableview animated:YES];
                                                              
                                                          }];
}
*/
//========================================
@end
